﻿Imports KFZ_Ausgaben.clsFunctions

Public Class frmMain
    Private m_pRefuelings As List(Of clsRefueling)
    Private m_pMisc As List(Of clsMisc)
    Private m_pColumnSorter As clsColumnSorter

    Private WithEvents m_pFrmSettings As frmSettings

    Private Sub Initialize()
        m_pRefuelings = New List(Of clsRefueling)
        m_pMisc = New List(Of clsMisc)

        If Not clsSettings.SettingsFileExists Then
            clsSettings.SetDefaultSettings(False)
            btnFuelSave.Enabled = True
            btnMiscSave.Enabled = True
        Else
            clsXmlWriter.ReadFromXml(clsSettings.Setting("datapath"), m_pRefuelings, m_pMisc)
        End If

        m_pColumnSorter = New clsColumnSorter
        m_pColumnSorter.Order = SortOrder.Ascending
        lvFuel.ListViewItemSorter = m_pColumnSorter


        ApplySettings()
        'ListRefuelings()
        ListMisc()

        ResetShowingYearBoundaries()
    End Sub

    Private Sub ResetShowingYearBoundaries()
        nudFuelYear.Minimum = GetYearOfFirstEntry(m_pRefuelings)
        nudFuelYear.Maximum = Math.Max(GetYearOfLastEntry(m_pRefuelings), Date.Now.Year)
        nudFuelYear.Value = Date.Now.Year
    End Sub

    Private Property Mileage As Single
        Get
            Return clsSettings.Setting("mileage")
        End Get
        Set(ByVal value As Single)
            clsSettings.Setting("mileage") = value
        End Set
    End Property

    Private Sub ApplySettings()
        txtNextInspection.Text = clsSettings.Setting("nextInspection")

        chFuelDate.Width = clsSettings.Setting("chFuelDateWidth")
        chFuelPrice.Width = clsSettings.Setting("chFuelPriceWidth")
        chFuelLiter.Width = clsSettings.Setting("chFuelLiterWidth")
        chFuelPricePerLiter.Width = clsSettings.Setting("chFuelPricePerLiterWidth")
        chFuelGasStation.Width = clsSettings.Setting("chFuelGasStationWidth")
        chFuelKilometer.Width = clsSettings.Setting("chFuelKilometerWidth")

        chMiscDate.Width = clsSettings.Setting("chMiscDateWidth")
        chMiscDescription.Width = clsSettings.Setting("chMiscDescriptionWidth")
        chMiscCost.Width = clsSettings.Setting("chMiscCostWidth")
        chMiscNote.Width = clsSettings.Setting("chMiscNoteWidth")
    End Sub

    Private Sub TryLoadOldData(ByVal sPath As String)
        Try
            Dim pOldData As clsOldDataContainer = clsOldDataContainer.LoadOldData(sPath)

            If pOldData Is Nothing Then Return

            pOldData.AssignToNewSettings()
            m_pRefuelings = pOldData.RefuelingList
            m_pMisc = pOldData.MiscList


            ApplySettings()

            ListRefuelings()
            ListMisc()

            btnFuelSave.Enabled = True
            btnMiscSave.Enabled = True

            MsgBox("Import abgeschlossen", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Import")

        Catch ex As Exception
            clsLogWriter.WriteLog(LogLevel.ERROR, "Beim Importieren alter Daten ist ein Fehler aufgetreten", ex)
            MsgBox("Importieren fehlgeschlagen", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Import")
        End Try
    End Sub

    Private Sub ListRefuelings()
        If m_pRefuelings Is Nothing Then Return

        Dim iShowingYear As Integer = nudFuelYear.Value

        lvFuel.BeginUpdate()

        lvFuel.Items.Clear()

        Dim pLVItem As ListViewItem = Nothing
        Dim pLVSubItem As ListViewItem.ListViewSubItem = Nothing

        Dim i As Integer = 0
        Dim x As Integer = -1

        For Each pRefueling In m_pRefuelings
            x += 1 ' Zählt auf den aktuellen Eintrag mit
            If Not (iShowingYear = 1337 Or iShowingYear = pRefueling.RefuelDate.Year) Then Continue For

            lvFuel.Items.Add(pRefueling.RefuelDate.ToString("dd.MM.yyyy"))
            lvFuel.Items(i).Tag = pRefueling

            With lvFuel.Items(i).SubItems
                pLVSubItem = .Add(FormatCurrency(pRefueling.Price))
                pLVSubItem.Tag = pRefueling.Price

                pLVSubItem = .Add(FormatUnit(pRefueling.Liter, "l"))
                pLVSubItem.Tag = pRefueling.Liter

                pLVSubItem = .Add(FormatCurrency(pRefueling.PricePerLiter, 3))
                pLVSubItem.Tag = pRefueling.PricePerLiter

                pLVSubItem = .Add(pRefueling.GasStation)
                pLVSubItem.Tag = pRefueling.GasStation

                ' Wenn es noch einen weiteren Eintrag gibt..
                If x + 1 < m_pRefuelings.Count Then
                    ' .. nimm den Kilometerstand aus dem Nachfolger
                    pLVSubItem = .Add(FormatUnit(m_pRefuelings(x + 1).LastDistance, "km"))
                    pLVSubItem.Tag = m_pRefuelings(x + 1).LastDistance
                Else
                    pLVSubItem = .Add(FormatUnit(0.0, "km"))
                    pLVSubItem.Tag = 0.0
                End If

            End With

            i += 1
        Next

        lvFuel.EndUpdate()
    End Sub

    Private Sub ListMisc()
        lvMisc.BeginUpdate()

        lvMisc.Items.Clear()

        Dim pLVItem As ListViewItem = Nothing

        For Each pMisc In m_pMisc
            pLVItem = lvMisc.Items.Add(pMisc.MiscDate.ToString("dd.MM.yyyy"))
            With pLVItem.SubItems
                .Add(pMisc.Description)
                .Add(FormatCurrency(pMisc.Cost))
                .Add(pMisc.Note)
            End With
        Next

        lvMisc.EndUpdate()
    End Sub

    Private Sub SortRefuelings()
        clsFunctions.SortRefueling(m_pRefuelings)
    End Sub

    Private Sub ShowAddRefuelEntryDialog()
        Dim pFrmNewFuelEntry As New frmNewFuelEntry

        pFrmNewFuelEntry.CreateGasStationList(m_pRefuelings)

        pFrmNewFuelEntry.ShowDialog()

        If pFrmNewFuelEntry.DialogResult = Windows.Forms.DialogResult.OK Then
            Dim pEntry As clsRefueling = pFrmNewFuelEntry.RefuelingEntry

            m_pRefuelings.Add(pEntry)

            SortRefuelings()

            ListRefuelings()

            btnFuelSave.Enabled = True
        End If
    End Sub
    Private Sub ShowEditRefuelEntryDialog()
        Dim pFrmEditRefuel As New frmNewFuelEntry

        Dim iFuelEntryIndex As Integer = m_pRefuelings.IndexOf(lvFuel.SelectedItems(0).Tag)

        Dim pFakeFuelEntry As clsRefueling = m_pRefuelings(iFuelEntryIndex).Clone
        If iFuelEntryIndex + 1 < m_pRefuelings.Count Then
            pFakeFuelEntry.LastDistance = m_pRefuelings(iFuelEntryIndex + 1).LastDistance
        Else
            pFakeFuelEntry.LastDistance = 0.0
        End If


        pFrmEditRefuel.CreateGasStationList(m_pRefuelings)
        pFrmEditRefuel.SetEntryToEdit(pFakeFuelEntry)
        pFrmEditRefuel.ShowDialog()

        If pFrmEditRefuel.DialogResult = Windows.Forms.DialogResult.OK Then
            pFakeFuelEntry = pFrmEditRefuel.RefuelingEntry

            If iFuelEntryIndex + 1 < m_pRefuelings.Count Then
                m_pRefuelings(iFuelEntryIndex + 1).LastDistance = pFakeFuelEntry.LastDistance
            End If

            pFakeFuelEntry.LastDistance = m_pRefuelings(iFuelEntryIndex).LastDistance
            m_pRefuelings(iFuelEntryIndex).AdoptValues(pFakeFuelEntry)

            ListRefuelings()

            btnFuelSave.Enabled = True
        End If
    End Sub
    Private Sub RecalculateStatistics()
        Try
            Dim dTotalCostFuel As Single = 0.0

            Dim dTotalKm As Single = 0.0
            Dim dTotalLiter As Single = 0.0

            Dim dAverageUsage As Single = 0.0

            For Each pRefuel In m_pRefuelings
                dTotalCostFuel += pRefuel.Price

                dTotalKm += pRefuel.LastDistance
                dTotalLiter += pRefuel.Liter

                If pRefuel.LastDistance > 0.0 Then
                    dAverageUsage = (dAverageUsage + (pRefuel.Liter / (pRefuel.LastDistance * 100.0))) / 2.0
                End If
            Next

            dAverageUsage = (dTotalLiter / dTotalKm) * 100.0


            Dim dTotalCostMisc As Single = 0.0

            For Each pMisc In m_pMisc
                dTotalCostMisc += pMisc.Cost
            Next


            lblCostFuel.Text = FormatCurrency(dTotalCostFuel)
            lblCostMisc.Text = FormatCurrency(dTotalCostMisc)
            lblCostTotal.Text = FormatCurrency(dTotalCostFuel + dTotalCostMisc)

            lblDrivenDistance.Text = FormatUnit(dTotalKm, "km", 1)
            lblKilometer.Text = FormatUnit(dTotalKm + Mileage, "km", 1)
            lblLiterTotal.Text = FormatUnit(dTotalLiter, "l")
            lblAverage.Text = FormatUnit(dAverageUsage, "l")
        Catch ex As Exception
            clsLogWriter.WriteLog(LogLevel.ERROR, "Beim Berechnen der Statistiken ist ein Fehler aufgetreten", ex)
        End Try
    End Sub

    Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If btnFuelSave.Enabled Or btnMiscSave.Enabled Then
            Dim rslt As DialogResult = MsgBox("Es gibt noch ungespeicherte Änderungen." + vbCrLf + "Möchten Sie diese Änderungen jetzt speichern?", vbYesNoCancel + MsgBoxStyle.Exclamation, "Änderungen speichern")

            If rslt = Windows.Forms.DialogResult.Yes Then
                savedata()


            ElseIf rslt = Windows.Forms.DialogResult.Cancel Then
                e.Cancel = True

            End If
        End If

        clsSettings.SaveSettings()
    End Sub


    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Initialize()
    End Sub
    Private Sub btnFuelAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFuelAdd.Click
        ShowAddRefuelEntryDialog()
    End Sub

    Private Sub lvFuel_ColumnClick(ByVal sender As Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs) Handles lvFuel.ColumnClick
        If e.Column = m_pColumnSorter.SortColumn Then
            If m_pColumnSorter.Order = SortOrder.Ascending Then
                m_pColumnSorter.Order = SortOrder.Descending
            ElseIf m_pColumnSorter.Order = SortOrder.Descending Then
                m_pColumnSorter.Order = SortOrder.Ascending
            End If
        Else
            m_pColumnSorter.SortColumn = e.Column
            m_pColumnSorter.Order = SortOrder.Ascending
        End If
        lvFuel.Sort()
    End Sub

    Private Sub lvFuel_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvFuel.DoubleClick
        ShowEditRefuelEntryDialog()
    End Sub

    Private Sub pTabControl_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles pTabControl.SelectedIndexChanged
        Select Case pTabControl.SelectedTab.Name
            Case "tpFuel"
                nudFuelYear.Enabled = True

            Case "tpMisc"
                nudFuelYear.Enabled = False

            Case "tpStatistics"
                nudFuelYear.Enabled = False
                RecalculateStatistics()

        End Select
    End Sub

    Private Sub nudFuelYear_ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles nudFuelYear.ValueChanged
        ListRefuelings()
    End Sub

    Private Sub BeendenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BeendenToolStripMenuItem.Click
        Me.Close()
    End Sub

    Private Sub EinstellungenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EinstellungenToolStripMenuItem.Click
        m_pFrmSettings = New frmSettings
        m_pFrmSettings.DataFolder = clsSettings.Setting("datapath")

        If m_pFrmSettings.ShowDialog = Windows.Forms.DialogResult.OK Then
            ApplySettingsChanges()
        End If

        m_pFrmSettings.Dispose()
    End Sub

    Private Sub ApplySettingsChanges()
        If m_pFrmSettings IsNot Nothing Then
            clsSettings.Setting("datapath") = m_pFrmSettings.DataFolder
        End If
    End Sub

    Private Sub m_pFrmSettings_ApplyPressed(ByVal sender As frmSettings) Handles m_pFrmSettings.ApplyPressed
        ApplySettingsChanges()
    End Sub

    Private Sub btnFuelSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFuelSave.Click
        SaveData()
    End Sub

    Private Sub SaveData()
        If clsSettings.Setting("datapath") Is Nothing Then
            MsgBox("Es ist noch kein Speicherpfad für die Daten angegeben worden." + vbCrLf + "Bitte geben Sie einen Pfad in den Einstellungen an" + vbCrLf + "und versuchen Sie es erneut.", MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation, "Speicherpfad nicht angegeben")
            Return
        End If
        clsXmlWriter.WriteToXml(clsSettings.Setting("datapath"), m_pRefuelings, m_pMisc)
        btnFuelSave.Enabled = False
        btnMiscSave.Enabled = False
    End Sub

    Private Sub btnMiscSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMiscSave.Click
        SaveData()
    End Sub

    Private Sub ImportierenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ImportierenToolStripMenuItem.Click
        pOpenFileDialog.Title = "Importdatei wählen"
        pOpenFileDialog.Filter = "KAD-Datei|*.kad"

        If pOpenFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
            TryLoadOldData(pOpenFileDialog.FileName)
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim pGraphForm As New frmGraph
        pGraphForm.ShowDialog()
    End Sub
End Class
